<template>
  <div class="main">
    <a-form
      id="formLogin"
      class="user-layout-login"
      ref="formLogin"
      :form="form"
      @submit="handleSubmit2"
    >
      <div class="tab-list" style="justify-content: center">
        <div
          class="tab-item"
          :class="{ active: index == tabIndex }"
          v-for="(item, index) in tabList"
          @click="toggleTab(index)"
          :key="index"
        >
          {{ item }}
          <p class="tab-dot" v-if="index == tabIndex"></p>
        </div>
      </div>
      <!-- <a-tabs
        :activeKey="customActiveKey"
        :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        @change="handleTabClick"
      >
        <a-tab-pane key="tab1" tab="账号密码登录"> -->
      <!-- <a-alert
            v-if="isLoginError"
            type="error"
            showIcon
            style="margin-bottom: 24px"
            message="账户或密码错误（admin )"
          /> -->
      <!-- <div class="form-item-title">登录账号/<span>NUMBER</span></div> -->
      <div v-if="tabIndex == 0">
        <a-form-item>
          <a-input
            size="large"
            type="text"
            @blur="handleBlur"
            placeholder="请输入账号"
            class="user-input"
            v-decorator="[
              'loginName',
              {
                rules: [{ required: true, message: '请输入账号' }],
                validateTrigger: 'blur'
              }
            ]"
          >
            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input>
        </a-form-item>
        <!-- <div class="form-item-title">密码/<span>PASSWORD</span></div> -->
        <a-form-item>
          <a-input-password
            size="large"
            autocomplete="false"
            placeholder="请输入密码"
            class="user-input"
            v-decorator="[
              'password',
              {
                rules: [{ required: true, message: '请输入密码' }],
                validateTrigger: 'blur'
              }
            ]"
          >
            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input-password>
        </a-form-item>
        <a-form-item v-if="showGoogleCode == true">
          <a-input
            size="large"
            type="text"
            placeholder="Google Auth Code"
            class="user-input"
            v-decorator="[
              'googleAuthCode',
              {
                rules: [{ required: true, message: '请输入google auth code' }],
                validateTrigger: 'blur'
              }
            ]"
          >
            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input>

          <a-button v-if="showGoogleBuild == true" @click="buildGoogleAuth">添加</a-button>
          
        </a-form-item>

        <!-- <a-form-item>
          <a-input
            size="large"
            type="text"
            class="user-input"
            placeholder="验证码"
            v-decorator="[
              'code',
              {
                rules: [{ required: true, message: '请输入验证码' }],
                validateTrigger: 'blur'
              }
            ]"
          >
            <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
            <template slot="suffix">
              <img :src="captchaImageSrc" class="captchaImage" @click="refreshCaptcha" />
            </template>
          </a-input>
          <!- <a-button
            class="getCaptcha"
            tabindex="-1"
            :disabled="state.smsSendBtn"
            @click.stop.prevent="getCaptcha"
          >
            {{ (!state.smsSendBtn && '获取验证码') || state.time + ' s' }}
          </a-button> --
        </a-form-item> -->
      </div>
      <!-- </a-tab-pane> -->
      <!-- <a-tab-pane key="tab2" tab="短信快捷登录"> -->
      <div v-if="tabIndex == 1">
        <a-form-item>
          <a-input
            size="large"
            type="text"
            class="user-input"
            placeholder="手机号"
            v-decorator="[
              'mobile',
              {
                rules: [
                  {
                    required: true,
                    pattern: /^1[34578]\d{9}$/,
                    message: '请输入正确的手机号'
                  }
                ],
                validateTrigger: 'change'
              }
            ]"
          >
            <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-input
            size="large"
            type="text"
            class="user-input"
            placeholder="验证码"
            v-decorator="[
              'captcha',
              {
                rules: [{ required: true, message: '请输入验证码' }],
                validateTrigger: 'blur'
              }
            ]"
          >
            <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input>
          <a-button
            class="getCaptcha"
            tabindex="-1"
            :disabled="state.smsSendBtn"
            @click.stop.prevent="getCaptcha"
          >
            {{ (!state.smsSendBtn && '获取验证码') || state.time + ' s' }}
          </a-button>
        </a-form-item>
        <!-- <a-row :gutter="16">
          <a-col class="gutter-row" :span="16">
            <a-form-item>
              <a-input size="large" type="text" class="user-input" placeholder="验证码" v-decorator="['captcha', {rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur'}]">
                <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-button
              class="getCaptcha"
              tabindex="-1"
              :disabled="state.smsSendBtn"
              @click.stop.prevent="getCaptcha"
            >
              {{ !state.smsSendBtn && '获取验证码' || (state.time+' s') }}
            </a-button>
          </a-col>
        </a-row> -->
        <!-- </a-tab-pane>
      </a-tabs> -->
      </div>
      <a-form-item style="margin-top: 24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
          >
          登录
          </a-button
        >
      </a-form-item>
    </a-form>


    <a-modal
      v-model="selectPlatVisible"
      title="请选择登录平台"
      ok-text="确认"
      cancel-text="取消"
      @ok="confirmSmsLogin"
    >
      <div class="select-plat-list">
        <a-radio-group v-model="selectPlatIndex" @change="onChange">
          <a-radio
            :style="radioStyle"
            v-for="(item, index) in selectPlatList"
            :value="index"
            :key="index"
          >
            {{ item.platform_name }}（{{ item.platform_code }}）
          </a-radio>
        </a-radio-group>
      </div>
    </a-modal>

    <google-auth v-if="googleAuthVisible"  @dgClose="dgClose" ref="googleAuth"></google-auth>
  </div>



</template>
<script>
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { getSmsCaptcha ,getUser} from '@/api/login'
import storage from 'store'

import GoogleAuth from "@/views/user/google-auth.vue";

// import sm4 from "sm-crypto/sm4"
const sm4 = require("sm-crypto").sm4;

// import { getSmsCaptcha, loginSms } from '@/api/login'

export default {
  components: {
    GoogleAuth
  },
  data() {
    return {
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false,
        code: '',
        random_str: new Date().getTime()
      },
      tabList: ['账号密码登录'],
      tabIndex: 0,
      selectPlatVisible: false,
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px'
      },
      selectPlatIndex: 0,
      selectPlatList: [],
      username: 'admin',
      timer: null,
      rememberMe: false,
      captchaImageSrc: '',
      googleAuthVisible: false,
      showGoogleBuild:false,
      showGoogleCode:false,
    }
  },
  created() {
    // get2step({})
    //   .then((res) => {
    //     this.requiredTwoStepCaptcha = res.result.stepCode
    //   })
    //   .catch(() => {
    //     this.requiredTwoStepCaptcha = false
    //   })
    this.requiredTwoStepCaptcha = true
  },
  mounted() {
    // this.refreshCaptcha()
    // if (this.getUserName()) {
    //   this.Logout().then(() => {
    //     this.handleSubmit()
    //   })
    // }
    // if (this.getJobNumber()) {
    //   this.Logout().then(() => {
    //     this.handleSubmit()
    //   })
    // }
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    refreshCaptcha() {
      this.state.random_str = new Date().getTime();
      this.captchaImageSrc =
        process.env.VUE_APP_API_BASE_URL +
        "/api/user/captcha?random_str=" +
        this.state.random_str;
    },

    handleBlur(){
      const loginName = this.form.getFieldValue('loginName');
      //检查是否绑定google
      const formData = new FormData();
      formData.append('userName', loginName);
      getUser(formData).then((res) =>{
        this.showGoogleCode = res.data != 0 ? true : false;
        this.showGoogleBuild = res.data == 1 ? true : false;
      }).catch(() => {
        this.showGoogleCode = false;
        this.showGoogleBuild = false;
      })

    },
     
    buildGoogleAuth () {
      const loginName = this.form.getFieldValue('loginName');
      console.log("loginName:{}",loginName)
        if(!loginName){
          alert("请输入用户名!")
          return ;
        }
        this.googleAuthVisible = true
        this.$nextTick(() => {
          this.$refs.googleAuth.init(loginName)
        })
    },

  dgClose(){
    this.googleAuthVisible=false;
  },
    // handler
    handleUsernameOrEmail(rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleSubmit2(e) {
      if (e) {
        e.preventDefault()
      }
      this.form.validateFields((err, values) => {
        console.log(values, 'values')
        if (!err) {
          this.state.loginBtn = true
          this.Login({
            // loginType: 'UN',
            ...values,
            name: values.loginName
            // password: sm4.encrypt(values.password, "fede9abd9f56b1dbdf7bb2f5b8c8c466"),
            // code: this.state.code,
            // randomStr: this.state.random_str
          })
            .then((res) => {
              // if(this.rememberMe){
              //   storage.set('SSIAuthUser', )
              //   storage.set('SSIAuth', this.getUserName())
              // }
              // this.refreshCaptcha()
              this.state.loginBtn = false
              this.loginSuccess(res)
            })
            .catch(() => {
              this.state.loginBtn = false
              // this.refreshCaptcha()
            })
        }
      })
    },
    handleTabClick(key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    handleSubmit(e) {
      if (e) {
        e.preventDefault()
      }

      const {
        // form: { validateFields },
        state,
        Login
      } = this

      Login({
        channel: 'web',
        SSIAuth: this.getUserName(),
        jobNumber: this.getJobNumber()
        // jobNumber: this.username
      })
        .then((res) => {
          console.log(res, 'success')
          storage.set('SSIAuth', this.getUserName())
          // this.loginSuccess(res)
        })
        .catch((err) => {
          console.log(err, 'error')
          this.requestFailed(err)
        })
        .finally(() => {
          state.loginBtn = false
        })
      // const validateFieldsKey =
      //   this.tabIndex === 0 ? ['username', 'password'] : ['mobile', 'captcha']

      // validateFields(validateFieldsKey, { force: true }, (err, values) => {
      //   if (!err) {
      //     state.loginBtn = true
      //     console.log('login form', values)
      //     // const loginParams = { ...values }
      //     // delete loginParams.username
      //     // loginParams[!state.loginType ? 'email' : 'username'] = values.username
      //     // loginParams.password = md5(values.password)
      //     const loginParams = {}
      //     if (this.tabIndex === 0) {
      //       loginParams.user_name = values.username
      //       loginParams.password = values.password
      //       loginParams.platform_code = ''
      //       loginParams.login_type = 'UN'
      //       loginParams.channel = 'admin'
      //       loginParams.system_code = 'S01'
      //       Login(loginParams)
      //         .then((res) => {
      //           console.log(res, 'success')
      //           this.loginSuccess(res)
      //         })
      //         .catch((err) => {
      //           console.log(err, 'error')
      //           this.requestFailed(err)
      //         })
      //         .finally(() => {
      //           state.loginBtn = false
      //         })
      //     } else {
      //       loginParams.login_phone = values.mobile
      //       loginParams.sms_code = values.captcha
      //       loginSms(loginParams)
      //         .then((res) => {
      //           console.log(res)
      //           // this.selectPlatVisible = true
      //           this.selectPlatList = res.data
      //           this.selectPlatIndex = 0
      //           this.confirmSmsLogin()
      //         })
      //         .finally(() => {
      //           state.loginBtn = false
      //         })
      //     }
      //   } else {
      //     setTimeout(() => {
      //       state.loginBtn = false
      //     }, 500)
      //   }
      // })
    },
    getCaptcha(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state
      } = this

      validateFields(['mobile'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          // const hide = this.$message.loading('验证码发送中..', 0)
          getSmsCaptcha({ login_phone: values.mobile, type: 2 })
            .then((res) => {
              console.log(res, 'success')
              this.$notification['success']({
                message: '提示',
                description: '验证码发送成功'
              })
              // setTimeout(hide, 2500)
              // this.$notification['success']({
              //   message: '提示',
              //   description: '验证码获取成功，您的验证码为：' + res.result.captcha,
              //   duration: 8
              // })
            })
            .catch((err) => {
              console.log(err, 'error')
              // setTimeout(hide, 1)
              // clearInterval(interval)
              // state.time = 60
              // state.smsSendBtn = false
              // this.requestFailed(err)
            })
        }
      })
    },
    stepCaptchaSuccess() {
      this.loginSuccess()
    },
    stepCaptchaCancel() {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    loginSuccess(res) {
      console.log(res)
      // check res.homePage define, set $router.push name res.homePage
      // Why not enter onComplete
      /*
      this.$router.push({ name: 'analysis' }, () => {
        console.log('onComplete')
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      })
      */
      // clearTimeout(this.timer)
      // this.timer = setTimeout(() => {
      //   this.Logout().then(() => {
      //     this.$router.push({
      //       path: '/user/login?SSIAuth=' + storage.get('SSIAuth')
      //     })
      //   })
      // }, 24 * 60 * 60 * 1000)
      if (res.userType === 'track') {
        this.$router.push({ path: '/dashboard/track/activite' })
      }else {
        this.$router.push({ name: 'indexIndex' })
      }
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
      this.isLoginError = false
    },
    requestFailed() {
      this.isLoginError = true
      // this.$notification['error']({
      //   message: '错误',
      //   description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
      //   duration: 4
      // })
    },
    toggleTab(index) {
      this.tabIndex = index
    },
    onChange(e) {
      this.selectPlatIndex = e.target.value
    },
    confirmSmsLogin() {
      this.selectPlatVisible = false
      const { Login } = this
      const loginParams = {
        channel: 'admin',
        login_type: 'UP',
        password: this.selectPlatList[this.selectPlatIndex].password,
        platform_code: this.selectPlatList[this.selectPlatIndex].platform_code,
        system_code: 'S01',
        user_name: this.selectPlatList[this.selectPlatIndex].username
      }
      Login(loginParams)
        .then((res) => {
          console.log(res, 'success')
          this.loginSuccess(res)
        })
        .catch((err) => {
          console.log(err, 'error')
          this.requestFailed(err)
        })
    },
    getUserName() {
      return this.getUrlParams(decodeURIComponent(location.href)).SSIAuth
    },
    getJobNumber() {
      return this.getUrlParams(decodeURIComponent(location.href)).jobNumber
    },
    getUrlParams(url) {
      // 通过 ? 分割获取后面的参数字符串
      const urlStr = url.split('?')[1]
      // 创建空对象存储参数
      const obj = {}
      // 再通过 & 将每一个参数单独分割出来
      if (urlStr) {
        const paramsArr = urlStr.split('&')
        for (let i = 0, len = paramsArr.length; i < len; i++) {
          // 再通过 = 将每一个参数分割为 key:value 的形式
          const arr = paramsArr[i].split('=')
          obj[arr[0]] = arr[1]
        }
      }
      return obj
    }
  }
}
</script>
<style lang="less" scoped>
.captchaImage {
  width: 100px;
  height: 100%;
  vertical-align: middle;
}
/deep/.ant-input-affix-wrapper .ant-input-suffix {
  height: 82%;
}
.form-item-title {
  font-size: 15px;
  color: #101d37;
  margin-bottom: 7px;
  span {
    color: #d5d5d5;
    margin-left: 2px;
  }
}
/deep/ .ant-form-item-children{
  display: flex;
  .ant-btn{
    margin: 7px 0 0 10px;
  }
}
.form-title {
  width: 180px;
  margin-bottom: 24px;
  img {
    width: 100%;
  }
}
.main {
  width: 480px !important;
  height: 600px;
  border-radius: 9px 9px 9px 9px;
  display: flex;
  justify-content: right;
  margin-right: 100px !important;
  .user-layout-login {
    padding: 70px 60px;
    box-sizing: border-box;
    float: left;
    background: #ffffff;
    height: 600px;
    border-radius: 9px;
    width: 480px;
    box-shadow: 11px 11px 67px 0px rgba(222, 224, 226, 1);
    /deep/ .user-input {
      height: 55px;
      line-height: 55px;
      position: relative;
      input {
        height: 55px;
        font-size: 16px;
        padding-left: 93px;
        border-radius: 38px;
        border: 1px solid #e0e0e0;
      }
      .ant-input-prefix {
        font-size: 30px;
        left: 25px;
        border-right: 1px solid #e3e3e3;
        padding-right: 15px;
      }
    }
    .tab-list {
      display: flex;
      height: 90px;
      .tab-item {
        width: 50%;
        height: 40px;
        text-align: center;
        font-size: 24px;
        color: #999;
        position: relative;
        cursor: pointer;
        .tab-dot {
          width: 24px;
          height: 6px;
          background: #5969f6;
          border-radius: 5px 0px 5px 0px;
          position: absolute;
          top: 40px;
          left: calc(50% - 12px);
        }
      }
      .tab-item.active {
        color: #333;
        font-weight: 500;
      }
    }
    /deep/ .self-checkbox {
      .ant-checkbox-inner {
        border-radius: 50%;
        width: 24px;
        height: 24px;
      }
      .ant-checkbox-checked .ant-checkbox-inner::after {
        left: 7px;
      }
    }
  }
}
.main-left {
  width: 400px;
  height: 420px;
  float: left;
  position: relative;
  > img {
    width: 100%;
    height: 100%;
  }
  &-name {
    position: absolute;
    top: 230px;
    left: 0;
    right: 0;
    text-align: center;
    margin: 0 auto;
    font-size: 40px;
    font-weight: bold;
    color: #ffffff;
    line-height: 55px;
    letter-spacing: 7px;
  }
  &-logo {
    position: absolute;
    left: 0;
    right: 0;
    width: 80px !important;
    height: 80px !important;
    background: #fff;
    top: 115px;
    border-radius: 50%;
    margin: 0 auto;
    img {
      width: 60px;
      height: 60px;
      margin: 10px;
    }
  }
}
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 120px;
    height: 50px;
    line-height: 50px;
    position: absolute;
    right: 1px;
    top: -17px;
    border: none;
    border-radius: 28px !important;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 54px;
    width: 100%;
    box-shadow: 3px 4px 18px 0px #c6defe;
    border-radius: 7px;
    border-radius: 38px;
    font-size: 22px;
    margin-top: 70px;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
@media screen and (max-width: 500px) {
  .main-left {
    display: none;
  }
}
</style>
